<template>
  <div class="space-y-4">
    <div v-for="item in filteredItems" :key="item.id" class="bg-gray-50 rounded-xl p-4 hover:bg-gray-100 transition-colors cursor-pointer" @click="handleOpen(item)">
      <!-- 角色信息头部 -->
      <div v-if="item.characterName || item.avatarUrl" class="flex items-center mb-3">
        <div v-if="item.avatarUrl" class="w-8 h-8 rounded-full overflow-hidden mr-3 flex-shrink-0">
          <img 
            :src="item.avatarUrl" 
            :alt="item.characterName || '角色头像'"
            class="w-full h-full object-cover"
            @error="handleImageError"
          />
        </div>
        <div v-if="item.characterName" class="text-sm font-medium text-gray-700">
          {{ item.characterName }}
        </div>
      </div>
      
      <!-- 对话内容 -->
      <p class="mt-1 text-sm text-gray-500 overflow-hidden" style="display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; line-clamp: 2;">{{ item.summary }}</p>
      <div class="mt-2 flex items-center justify-between text-xs text-gray-400">
        <div>{{ item.time }}</div>
        <button 
          @click="handleFavorite(item)"
          class="h-7 w-7 rounded-lg hover:bg-gray-200 text-amber-500 flex items-center justify-center" 
          title="收藏"
        >
          ★
        </button>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-if="filteredItems.length === 0" class="text-center py-12 text-gray-500">
      <svg class="w-12 h-12 mx-auto mb-4 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
      </svg>
      <p>暂无对话历史</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'

interface HistoryItem {
  id: number
  title: string
  summary: string
  time: string
  characterId?: number | string
  chatId?: string
  characterName?: string
  avatarUrl?: string
}

const props = defineProps<{
  items: HistoryItem[]
  searchKeyword?: string
}>()

const emit = defineEmits<{
  'favorite': [item: HistoryItem]
  'open': [item: HistoryItem]
}>()

// 过滤后的数据
const filteredItems = computed(() => {
  if (!props.searchKeyword) return props.items
  
  return props.items.filter(item => 
    item.title.toLowerCase().includes(props.searchKeyword!.toLowerCase()) ||
    item.summary.toLowerCase().includes(props.searchKeyword!.toLowerCase())
  )
})

const handleFavorite = (item: HistoryItem) => {
  emit('favorite', item)
}

const handleOpen = (item: HistoryItem) => {
  emit('open', item)
}

const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.style.display = 'none'
}
</script>
